
class Snake {

    //蛇头
    head: HTMLElement;

    //蛇身体
    bodies: HTMLCollection;

    //蛇的容器
    element: HTMLElement;

    constructor() {
        this.element = document.getElementById('snake')!
        this.head = document.querySelector('#snake > div') as HTMLElement;
        this.bodies = this.element.getElementsByTagName('div') as HTMLCollection;

    }

    get X() {
        return this.head.offsetLeft;

    }
    get Y() {
        return this.head.offsetTop;
    }
    set X(value: number) {
        if (this.X == value) return;

        if (value < 0 || value > 290) {
            throw new Error('蛇撞到墙了！');
        }

        //左右发生掉头修正canshu
        if (this.bodies.length > 1 && (this.bodies[1] as HTMLElement).offsetLeft == value) {
            console.log('发生了水平方向调头');

            if (value > this.X) {
                console.log('向左移动中，  按了向右 修正参数');

                value = this.X - 10;
            } else {
                value = this.X + 10;
            }
        }


        this.bodyMove();
        this.head.style.left = value + 'px';
        this.checkHead();

    }
    set Y(value: number) {
        if (this.Y == value) return;
        if (value < 0 || value > 290) {
            throw new Error('蛇撞到墙了！');
        }
        //左右发生掉头修正canshu
        if (this.bodies.length > 1 && (this.bodies[1] as HTMLElement).offsetTop == value) {

            if (value > this.Y) {

                value = this.Y - 10;
            } else {
                value = this.Y + 10;
            }
        }

        this.bodyMove();
        this.head.style.top = value + 'px';
        this.checkHead();

    }

    addBody() {
        this.element.insertAdjacentHTML('beforeend', "<div></div>");
        console.log(this.bodies);

    }

    bodyMove() {
        console.log(this.bodies.length, 'bodyMove');

        //4-> 3  3->2  2->1
        for (let i = this.bodies.length - 1; i > 0; i--) {

            //获取前面身体的位置
            let x = (this.bodies[i - 1] as HTMLElement).offsetLeft;
            let y = (this.bodies[i - 1] as HTMLElement).offsetTop;

            //设置到当前身体上
            (this.bodies[i] as HTMLElement).style.left = x + 'px';
            (this.bodies[i] as HTMLElement).style.top = y + 'px';
        }
    }

    //检查蛇头是否撞到身体
    checkHead() {
        for (let i = 1; i < this.bodies.length; i++) {
            let bd = this.bodies[i] as HTMLElement;
            if(this.X==bd.offsetLeft && this.Y==bd.offsetTop){
                throw new Error('蛇撞到身体了');
            }
        }
    }
}


export default Snake;


